package com.ztc.ZtcSpecialRecommendation.service;

import com.aqgj.Attachment.bean.Attachment;
import com.aqgj.Attachment.dao.AttachmentDao;
import com.aqgj.util.JsonWrapper;
import com.ztc.ZtcSpecialRecommendation.bean.ZtcSpecialRecommendation;
import com.ztc.ZtcSpecialRecommendation.dao.ZtcSpecialRecommendationDao;
import org.apache.commons.codec.binary.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Encoder;

import java.math.BigDecimal;
import java.util.*;

@Service("ZtcSpecialRecommendation")
public class ZtcSpecialRecommendationManager {

  @Autowired
  private ZtcSpecialRecommendationDao ztcSpecialRecommendationDao;
  @Autowired
  private AttachmentDao attachmentDao;

  public String save(ZtcSpecialRecommendation ztcSpecialRecommendation){
    return ztcSpecialRecommendationDao.save(ztcSpecialRecommendation);
  }

  //搜索线路站点信息（新增特价推荐）
  public HashMap<String,Object> searchClassForSale(String startSite, String endSite) {
    return JsonWrapper.successWrapper(ztcSpecialRecommendationDao.searchClassForSaleBySite(startSite,endSite));
  }

  public List<ZtcSpecialRecommendation> findBy(String propertyName, Object value) {
    return ztcSpecialRecommendationDao.findBy(propertyName, value);
  }

  public List<ZtcSpecialRecommendation> getZtcSpecialListByRoutId(String routeId,String startId,String endId,Integer type) {
    return ztcSpecialRecommendationDao.getZtcSpecialListByRoutId(routeId, startId,endId,type);
  }

  public void delete(String id){  ztcSpecialRecommendationDao.removeById(id); }

  public ZtcSpecialRecommendation get(String id){  return ztcSpecialRecommendationDao.get(id); }

  //获取所有正常推荐
  public HashMap<String, Object> getSpecialALLList(Integer type) {
    List<Map> result = ztcSpecialRecommendationDao.getSpecialALLList(type);
    List<Map> mapList = Collections.emptyList();

    //isExitList判断相同线路的所有班次
    List<String> isExitList = new ArrayList<>();
    if (result.size() > 0) {
      mapList = new ArrayList<>();
      one:for (Map map : result) {
        //特价推荐img
        if ("1".equals(map.get("type").toString())) {
          List<Attachment> attachmentList = attachmentDao.findBy("businessId", map.get("id").toString(), "workItem", "specialImg");
          if (attachmentList.size() > 0) {
            map.put("img", getFileBody(attachmentList.get(0).getFileBody()));
          }
        }

        //座位最低价格
        String[] tempSeat = map.get("seat_info").toString().split("\\),");
        List<BigDecimal> priceList = new ArrayList<>();
        if (tempSeat.length > 0) {
          for (String seat : tempSeat) {
            String[] seatArray = seat.split(",");
            if (seatArray.length == 4) {
              priceList.add(new BigDecimal(seatArray[2]));
            }
          }
        }

        if (isExitList.size() > 0) {
          //当次循环，(特价ID)判断相同线路还是否存在多条班次
          String routeObj = map.get("id").toString();
          //相同线路的班次
          if (isExitList.contains(routeObj)) {
            BigDecimal once= Collections.min(priceList);
            two:for (Map m : mapList) {
              if (m.get("id").toString().equals(map.get("id").toString())){
                BigDecimal ago=new BigDecimal(m.get("price").toString());
               if(ago.compareTo(once)==1){
                 m.replace("price",once);
                 m.replace("departureDate",map.get("departureDate").toString());
               }
               break two;
              }
            }
            //如果isExitList，这次循环result不添加到mapList
            continue one;
          } else {
            //前面的循环没有则添加
            isExitList.add(routeObj);
          }
        //第一次循环
        } else {
          String routeObj = map.get("id").toString();
          isExitList.add(routeObj);
        }

        map.put("price", Collections.min(priceList));
        map.remove("seat_info");
        mapList.add(map);
      }
    }
    return JsonWrapper.successWrapper(mapList);
  }



  /**
   * 解密base64位
   * @param fileBody 附件base64位图片数据
   * @return 解密后的base64位图片数据
   */
  private String getFileBody(byte[] fileBody) {
    for (int j = 0; j < fileBody.length; ++j) {
      if (fileBody[j] > 0) {
        // 调整异常数据
        fileBody[j] -= 256;
      }
    }
    String bodyInfo = org.apache.commons.codec.binary.Base64.encodeBase64String(fileBody);
    return bodyInfo;
  }

}
